package com.you.raft.client;


import com.you.raft.common.entity.ClientRequest;
import com.you.raft.common.entity.ClientResponse;
import com.you.raft.common.entity.Request;
import com.you.raft.common.entity.Response;
import com.you.rpc.RpcClient;
import com.you.raft.client.config.SystemConstant;

import java.util.Scanner;

import static com.you.raft.client.constant.MessageConstant.*;

public class ClientStarter {
    /**
     * 客户端-随意连接raft集群中的一个地址
     * <p>
     * 支持的指令:put/get,使用案例:
     * <p>
     * put x 100
     * <p>
     * get x
     */

    public static void main(String[] args) throws Exception {
        System.setProperty(SystemConstant.ADDRESS, "localhost:10001");
        start();
    }

    public static void start() throws Exception {
        //初始化RPC客户端
        RpcClient client = new RpcClient();
        client.start();
        String address = System.getProperty(SystemConstant.ADDRESS);
        client.connect(address);
        //初始化请求
        ClientRequest clientRequest = new ClientRequest();
        Request request = new Request();
        request.setCmd(Request.CLIENT_ORDER);
        request.setObj(clientRequest);
        request.setAddr(address);
        //获取控制台输入
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String code = scanner.nextLine();
            String[] metaData = code.split("\\s+");
            String cmd = metaData[0];
            if (cmd.equalsIgnoreCase(ClientRequest.Type.PUT.name())) {
                if (metaData.length != 3) {
                    System.out.println(ERROR_FORMAT);
                    continue;
                }
                String key = metaData[1], value = metaData[2];
                clientRequest.setType(ClientRequest.Type.PUT.getCode());
                clientRequest.setKey(key);
                clientRequest.setValue(value);
            } else if (cmd.equalsIgnoreCase(ClientRequest.Type.GET.name())) {
                if (metaData.length != 2) {
                    System.out.println(ERROR_FORMAT);
                    continue;
                }
                String key = metaData[1];
                clientRequest.setType(ClientRequest.Type.GET.getCode());
                clientRequest.setKey(key);
            } else {
                System.out.println(ERROR_NO_COMMAND);
                continue;
            }
            Response<ClientResponse> response = (Response<ClientResponse>) client.invokeSync(address, request);
            if (response != null) {
                ClientResponse result = response.getResult();
                String ans = result.getResult();
                System.out.println(ans);
            } else {
                System.out.println(ERROR_REQUEST);
            }
        }
    }
}
